﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HZY.EFCore
{
    using HZY.EFCore.Entitys.Sys;
    using HZY.EFCore.Entitys.Base;
    using Microsoft.EntityFrameworkCore;
    using System.Linq;
    using System.Threading.Tasks;

    public class HZYAppContext : DbContext
    {
        public static Dictionary<string, string> FieldComment { get; set; } = new Dictionary<string, string>();

        public HZYAppContext(DbContextOptions<HZYAppContext> options)
            : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //modelBuilder.Entity<Sys_AppLog>().ToTable("Sys_AppLog");
            //modelBuilder.Entity<User>().ToTable("User");

            #region 计算出 字段 注释中的中文名称

            //配置实体的 XML 信息
            var types = modelBuilder.Model.GetEntityTypes();
            foreach (var item in types)
            {
                var propertyInfos = item.ClrType.GetProperties();

                foreach (var propertyInfo in propertyInfos)
                {
                    var Name = Toolkit.ReadXmlSummary.XMLForMember(propertyInfo)?.InnerText?.Trim()?.Split("=>")?[0];
                    if (!string.IsNullOrWhiteSpace(Name))
                    {
                        var Key = $"{item.ClrType.Name}=>{propertyInfo.Name}";
                        FieldComment[Key] = Name;
                    }
                }
            }

            #endregion

        }


        #region DbSet

        public DbSet<Sys_AppLog> Sys_AppLogs { get; set; }
        public DbSet<Sys_Function> Sys_Functions { get; set; }
        public DbSet<Sys_Menu> Sys_Menus { get; set; }
        public DbSet<Sys_MenuFunction> Sys_MenuFunctions { get; set; }
        public DbSet<Sys_Role> Sys_Roles { get; set; }
        public DbSet<Sys_RoleMenuFunction> Sys_RoleMenuFunctions { get; set; }
        public DbSet<Sys_User> Sys_Users { get; set; }
        public DbSet<Sys_UserRole> Sys_UserRoles { get; set; }

        //
        public DbSet<Member> Members { get; set; }

        #endregion

        public async Task<TableViewModel> GetTableViewModel<T>(IQueryable<T> query, int Page, int Rows, params Type[] EntityTypes)
        {
            var _tableViewModel = new TableViewModel();

            _tableViewModel.Page = Page;
            _tableViewModel.Rows = Rows;
            _tableViewModel.TotalCount = await query.CountAsync();
            _tableViewModel.TotalPage = (_tableViewModel.TotalCount / Rows);

            var Datas = await query.Skip((Page - 1) * Rows).Take(Rows).ToListAsync();

            #region 组合一下 类型的属性和类型名称
            var TabAndField = new List<(string, string)>();
            foreach (var item in EntityTypes)
            {
                foreach (var prop in item.GetProperties())
                {
                    TabAndField.Add((prop.Name, item.Name));
                }
            }
            #endregion

            #region 填充 列 信息

            var type = typeof(T);
            var fields = type.GetProperties();

            foreach (var field in fields)
            {
                var tableName = TabAndField.Find(w => w.Item1 == field.Name).Item2;

                var key = $"{tableName}=>{field.Name}";

                var title = FieldComment.ContainsKey(key) ? FieldComment[key] : string.Empty;

                _tableViewModel.Cols.Add(new TableViewCol()
                {
                    ColName = field.Name,
                    Show = field.Name != "_ukid",
                    Title = string.IsNullOrWhiteSpace(title) ? field.Name : title
                });
            }

            #endregion

            #region 和数据转换为 list dic

            foreach (var item in Datas)
            {
                var dic = new Dictionary<string, object>();
                foreach (var field in fields) dic[field.Name] = field.GetValue(item);
                _tableViewModel.DataSource.Add(dic);
            }

            #endregion

            return _tableViewModel;
        }




    }
}
